package org.jeecg.modules.wms.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.wms.entity.FinishedGoodsInventory;
import org.jeecg.modules.wms.entity.FinishedGoodsInventoryLog;
import org.jeecg.modules.wms.service.IFinishedGoodsInventoryLogService;
import org.jeecg.modules.wms.service.IFinishedGoodsInventoryService;
import org.jeecg.modules.wms.vo.InventoryAdjustVO;
import org.jeecg.modules.wms.vo.InventoryQueryParam;
import org.jeecg.modules.wms.vo.CustomerInventoryGroup;
import org.jeecg.modules.wms.vo.HierarchicalInventoryQueryParam;
import org.jeecg.modules.wms.vo.InventoryStatisticsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 成品库存管理Controller
 */
@Api(tags = "成品库存管理")
@RestController
@RequestMapping("/wms/finished-goods/inventory")
@Slf4j
public class FinishedGoodsInventoryController extends JeecgController<FinishedGoodsInventory, IFinishedGoodsInventoryService> {

    @Autowired
    private IFinishedGoodsInventoryService inventoryService;

    @Autowired
    private IFinishedGoodsInventoryLogService inventoryLogService;

    /**
     * 分页查询成品库存列表
     */
    @ApiOperation(value = "分页查询成品库存列表", notes = "分页查询成品库存列表")
    @GetMapping(value = "/list")
    public Result<IPage<FinishedGoodsInventory>> queryPageList(InventoryQueryParam param,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                              HttpServletRequest req) {
        Page<FinishedGoodsInventory> page = new Page<>(pageNo, pageSize);
        IPage<FinishedGoodsInventory> pageList = inventoryService.queryInventoryList(page, param);
        return Result.OK(pageList);
    }

    /**
     * 移动端分层查询成品库存（按客户-订单分组）
     */
    @GetMapping("/queryHierarchicalForMobile")
    @ApiOperation(value = "移动端分层查询成品库存", notes = "按客户-订单分组查询成品库存")
    public Result<List<CustomerInventoryGroup>> queryHierarchicalForMobile(
            @ModelAttribute HierarchicalInventoryQueryParam param,
            HttpServletRequest req) {
        List<CustomerInventoryGroup> result = inventoryService.queryHierarchicalInventoryForMobile(param);
        
        return Result.OK(result);
    }

    /**
     * Web端分层查询成品库存（按客户-订单分组，支持分页）
     */
    @GetMapping("/queryHierarchicalForWeb")
    @ApiOperation(value = "Web端分层查询成品库存", notes = "按客户-订单分组查询成品库存，支持分页")
    public Result<IPage<CustomerInventoryGroup>> queryHierarchicalForWeb(
            @ModelAttribute HierarchicalInventoryQueryParam param,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        Page<CustomerInventoryGroup> page = new Page<>(pageNo, pageSize);
        IPage<CustomerInventoryGroup> result = inventoryService.queryHierarchicalInventoryForWeb(page, param);
        
        return Result.OK(result);
    }

    /**
     * 按订单查询库存分布
     */
    @ApiOperation(value = "按订单查询库存分布", notes = "按订单查询库存分布")
    @GetMapping(value = "/by-order/{orderNo}")
    public Result<List<FinishedGoodsInventory>> queryByOrder(@PathVariable("orderNo") String orderNo) {
        List<FinishedGoodsInventory> list = inventoryService.queryInventoryByOrder(orderNo);
        return Result.OK(list);
    }

    /**
     * 库存调整
     */
    @ApiOperation(value = "库存调整", notes = "库存调整")
    @PostMapping(value = "/adjust")
    public Result<String> adjustInventory(@Valid @RequestBody InventoryAdjustVO adjustVO) {
        try {
            inventoryService.adjustInventory(adjustVO);
            return Result.OK("库存调整成功");
        } catch (Exception e) {
            log.error("库存调整失败", e);
            return Result.error("库存调整失败：" + e.getMessage());
        }
    }

    /**
     * 按仓库统计库存
     */
    @ApiOperation(value = "按仓库统计库存", notes = "按仓库统计库存")
    @GetMapping(value = "/statistics/warehouse")
    public Result<List<InventoryStatisticsVO>> statisticsByWarehouse() {
        List<InventoryStatisticsVO> list = inventoryService.statisticsByWarehouse();
        return Result.OK(list);
    }

    /**
     * 按订单统计库存
     */
    @ApiOperation(value = "按订单统计库存", notes = "按订单统计库存")
    @GetMapping(value = "/statistics/order")
    public Result<List<InventoryStatisticsVO>> statisticsByOrder() {
        List<InventoryStatisticsVO> list = inventoryService.statisticsByOrder();
        return Result.OK(list);
    }

    /**
     * 按门窗系列统计库存
     */
    @ApiOperation(value = "按门窗系列统计库存", notes = "按门窗系列统计库存")
    @GetMapping(value = "/statistics/window-series")
    public Result<List<InventoryStatisticsVO>> statisticsByWindowSeries() {
        List<InventoryStatisticsVO> list = inventoryService.statisticsByWindowSeries();
        return Result.OK(list);
    }

    /**
     * 获取库存总览统计
     */
    @ApiOperation(value = "获取库存总览统计", notes = "获取库存总览统计")
    @GetMapping(value = "/statistics/overview")
    public Result<InventoryStatisticsVO> getInventoryOverview() {
        InventoryStatisticsVO overview = inventoryService.getInventoryOverview();
        return Result.OK(overview);
    }

    /**
     * 查询低库存预警
     */
    @ApiOperation(value = "查询低库存预警", notes = "查询低库存预警")
    @GetMapping(value = "/low-stock-warning")
    public Result<List<FinishedGoodsInventory>> queryLowStockWarning(@RequestParam(name = "threshold", defaultValue = "10") Integer threshold) {
        List<FinishedGoodsInventory> list = inventoryService.queryLowStockWarning(threshold);
        return Result.OK(list);
    }

    /**
     * 预留库存
     */
    @ApiOperation(value = "预留库存", notes = "预留库存")
    @PostMapping(value = "/reserve")
    public Result<String> reserveInventory(@RequestParam("inventoryId") String inventoryId,
                                          @RequestParam("quantity") Integer quantity,
                                          @RequestParam("reason") String reason) {
        try {
            boolean success = inventoryService.reserveInventory(inventoryId, quantity, reason);
            if (success) {
                return Result.OK("库存预留成功");
            } else {
                return Result.error("库存预留失败");
            }
        } catch (Exception e) {
            log.error("库存预留失败", e);
            return Result.error("库存预留失败：" + e.getMessage());
        }
    }

    /**
     * 释放预留库存
     */
    @ApiOperation(value = "释放预留库存", notes = "释放预留库存")
    @PostMapping(value = "/release-reserved")
    public Result<String> releaseReservedInventory(@RequestParam("inventoryId") String inventoryId,
                                                  @RequestParam("quantity") Integer quantity,
                                                  @RequestParam("reason") String reason) {
        try {
            boolean success = inventoryService.releaseReservedInventory(inventoryId, quantity, reason);
            if (success) {
                return Result.OK("预留库存释放成功");
            } else {
                return Result.error("预留库存释放失败");
            }
        } catch (Exception e) {
            log.error("预留库存释放失败", e);
            return Result.error("预留库存释放失败：" + e.getMessage());
        }
    }

    /**
     * 查询库存变动记录
     */
    @ApiOperation(value = "查询库存变动记录", notes = "查询库存变动记录")
    @GetMapping(value = "/logs")
    public Result<IPage<FinishedGoodsInventoryLog>> queryInventoryLogs(@RequestParam(name = "inventoryId", required = false) String inventoryId,
                                                                      @RequestParam(name = "orderNo", required = false) String orderNo,
                                                                      @RequestParam(name = "operationType", required = false) Integer operationType,
                                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<FinishedGoodsInventoryLog> page = new Page<>(pageNo, pageSize);
        IPage<FinishedGoodsInventoryLog> pageList = inventoryLogService.queryInventoryLogList(page, inventoryId, orderNo, operationType,null);
        return Result.OK(pageList);
    }

    /**
     * 查询指定库存的变动记录
     */
    @ApiOperation(value = "查询指定库存的变动记录", notes = "查询指定库存的变动记录")
    @GetMapping(value = "/logs/{inventoryId}")
    public Result<List<FinishedGoodsInventoryLog>> queryLogsByInventoryId(@PathVariable("inventoryId") String inventoryId) {
        List<FinishedGoodsInventoryLog> list = inventoryLogService.queryLogsByInventoryId(inventoryId);
        return Result.OK(list);
    }

    /**
     * 根据ID查询库存详情
     */
    @ApiOperation(value = "根据ID查询库存详情", notes = "根据ID查询库存详情")
    @GetMapping(value = "/detail/{id}")
    public Result<FinishedGoodsInventory> queryById(@PathVariable("id") String id) {
        FinishedGoodsInventory inventory = inventoryService.getById(id);
        if (inventory == null) {
            return Result.error("库存记录不存在");
        }
        return Result.OK(inventory);
    }

    /**根据orderDetailId获取库存
     */
    @ApiOperation(value = "根据orderDetailId获取库存", notes = "根据orderDetailId获取库存")
    @GetMapping(value = "/by-order-detail/{orderDetailId}")
    public Result<List<FinishedGoodsInventory>> queryByOrderDetailId(@PathVariable("orderDetailId") String orderDetailId) {
        List<FinishedGoodsInventory> inventory = inventoryService.queryByOrderDetailId(orderDetailId);

        if (inventory == null) {
            return Result.error("库存记录不存在");
        }
        return Result.OK(inventory);
    }

    /**
     * 获取成品业务统计信息
     */
    @ApiOperation(value = "获取成品业务统计信息", notes = "获取成品入库单和出库单总数统计")
    @GetMapping(value = "/statistics/business")
    public Result<java.util.Map<String, Object>> getFinishedGoodsBusinessStatistics() {
        try {
            java.util.Map<String, Object> statistics = new java.util.HashMap<>();
            
            // 获取成品入库单总数
            Long inboundCount = inventoryService.getFinishedGoodsInboundOrderCount();
            statistics.put("finishedInboundCount", inboundCount != null ? inboundCount : 0);
            
            // 获取成品出库单总数  
            Long outboundCount = inventoryService.getFinishedGoodsOutboundOrderCount();
            statistics.put("finishedOutboundCount", outboundCount != null ? outboundCount : 0);
            
            return Result.OK(statistics);
        } catch (Exception e) {
            log.error("获取成品业务统计信息失败", e);
            return Result.error("获取成品业务统计信息失败：" + e.getMessage());
        }
    }
}
